#include <stdio.h>
#include <stdlib.h>
//#include <malloc.h>
#include "queue1.h"

static void copyToNode(const Item item,Node *pnode);
static void copyToItem(Node *pnode,Item *pitem);

void createQueue(Queue *pq)
{
	pq->front = pq->rear = NULL;
	pq->len = 0;
}

BOOL qIsFull(Queue *pq)
{
	return pq->len == MAX_QSIZE;
}

BOOL qIsEmpty(Queue *pq)
{
	return pq->len == 0;
}

int queue_length(Queue *pq)
{
	return pq->len;
}

BOOL enItem(Queue *pq,const Item item)
{
	Node *pnode = (Node *)malloc(sizeof(Node));
	if (pnode == NULL){
		fprintf(stderr,"malloc error\n");
		return FALSE;
	}
	if (qIsFull(pq)){
        free(pnode);
		return FALSE;
    }
	copyToNode(item,pnode);
	pnode->next = NULL;
	if (qIsEmpty(pq))
		pq->front = pnode;
	else
		pq->rear->next = pnode;
	pq->rear = pnode;
	pq->len++;
	return TRUE;
}

BOOL deItem(Queue *pq,Item *pitem)
{
	Node *pnode;
	if (qIsEmpty(pq))
		return FALSE;
	copyToItem(pq->front,pitem);
	pnode = pq->front->next;
	free(pq->front);
	pq->front = pnode;
	pq->len--;
	if (pq->len == 0){
		pq->rear = NULL;
	}
	return TRUE;
}

void destroyQueue(Queue *pq)
{
	Item temp;
	while(!qIsEmpty(pq)){
		deItem(pq,&temp);
	}
}

static void copyToNode(const Item item,Node* pnode)
{
	pnode->item = item;
}

static void copyToItem(Node *pnode,Item *pitem)
{
	*pitem = pnode->item;
}



